import * as signalR from '@microsoft/signalr'
interface SignalRService {
  SR: signalR.HubConnection;
  failNum: number;
  init(): void;
  start(): Promise<boolean>;
}

const signalRService: SignalRService = {
  // signalR对象
  SR: {} as signalR.HubConnection,
  
  // 失败连接重试次数
  failNum: 100,
  
  init() {
    const connection = new signalR.HubConnectionBuilder()
      .withUrl('http://localhost:18010/msgHub')
      .build();
      
    this.SR = connection;
    
    // 断线重连
    connection.onclose(async (error) => {
      console.error('断开连接了' + error);
      console.assert(connection.state === signalR.HubConnectionState.Disconnected);
      // 建议用户重新刷新浏览器
      await this.start();
    });
    
    connection.onreconnecting(async () => {
      console.log('断线重新连接中...');
      await this.start();
    });
    
    // 启动连接
    this.start();
  },
  
  /**
   * 调用 this.signalR.start().then(async () => { await this.SR.invoke("method")})
   * @returns
   */
  async start() {
    try {
      console.log('signalR-1', this.SR.state);
      // 使用async和await 或 promise的then 和catch 处理来自服务端的异常
      if (this.SR.state === signalR.HubConnectionState.Disconnected) {
        await this.SR.start();
      }
      console.log('signalR-2', this.SR.state);
      return true;
    } catch (error) {
      console.error(error);
      this.failNum--;
      // console.log(`失败重试剩余次数${this.failNum}`, error)
      if (this.failNum > 0 && this.SR.state === signalR.HubConnectionState.Disconnected) {
        setTimeout(async () => {
          await this.start();
        }, 5000);
      }
      return false;
    }
  }
}

export default signalRService;